package cn.jlonely.xyhx.admin.service.impl;

import cn.jlonely.xyhx.admin.mapper.AdminMapper;
import cn.jlonely.xyhx.pojo.Admin;
import cn.jlonely.xyhx.pojo.vo.AdminVo;
import cn.jlonely.xyhx.admin.service.AdminService;
import cn.jlonely.xyhx.utils.JwtUtils;
import cn.jlonely.xyhx.utils.SHA256Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;
    @Override
    public AdminVo login(Admin admin) throws Exception {
        // 对输入的密码进行加密
        String encryptedPassword = SHA256Util.sha256(admin.getPassword());
        // 设置加密后的密码到 Admin 对象中
        admin.setPassword(encryptedPassword);

        // 根据用户名和加密后的密码查询数据库
        Admin a = adminMapper.selectByUsernameAndPassword(admin);

        //生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", a.getId());
        claims.put("username", a.getUsername());
        String jwt =  JwtUtils.generateJwt(claims);

        if (a != null) {
            return new AdminVo(
                    a.getId(),
                    a.getUsername(),
                    a.getName(),
                    a.getEmail(),
                    a.getPhoneNumber(),
                    a.getAvatarUrl(),
                    a.getCreateTime(),
                    a.getUpdateTime(),
                    jwt

            );
        }
        return null; 
    }

    @Override
    public void updateInfo(Admin admin) throws Exception {
        if (admin.getPassword() != null){
            admin.setPassword(SHA256Util.sha256(admin.getPassword()));
        }
        adminMapper.updateAdminInfo(admin);
    }

}
